﻿
/// <reference path="jquery-1.5.1.min.js" />
/// <reference path="jquery-1.5.1-vsdoc.js" />


var global_open_mode = 1; //1 为打开新选项卡方式  2 为在本地页面跳转


//init
$(function () {
    setDialogHeight();
})

function setDialogHeight() {
    //自适应窗口大小
    var height = $("#container").height();
    if (height < 650)
        height = 650;

    try {
        parent.setDialogHeight(height);
    }
    catch (ex) {

    }
}


/* 初始表格 */
function initTable(selector) {
    var sl = $(selector);

    $("tbody tr:odd", sl).css("background-color", "#F0F0F0");
}



/* 系统窗口操作 */

//重定向到指定的URL
function redirectUrl(url) {
    window.location = url;
}

//显示窗口
function openDialog(url, refresh) {
    showHead = false;
    var opt = { name: "", url: url, template: 1, showHead: showHead, isModal: false, parentTabUrl: "", refresh: false, closeRefresh: refresh };
    parent.addTab2(opt);
}

//新开tab 窗口，tabName 标签名字，url 打开的路径，refreshParent 是否刷新源页面
function openTab(tabName, url, refreshParent) {
    if (global_open_mode == 2) {  //在本地页面打开新窗口
        window.location = url;
        return;
    }

    showHead = true;
    var opt = { name: tabName, url: url, template: 1, showHead: showHead, isModal: false, parentTabUrl: "", refresh: false, closeRefresh: refreshParent };
    parent.addTab2(opt);
}

function closeTab() {
    parent.closeCurrentTab();
}

/*----------------- jquery 插件 对于查询搜索框设计的查询按钮 -----------------------------------

调用方式：
$.Dialog.open("标题【可选】","内容","显示时间，毫秒【可选】,'显示的图标 alert,error【可选】'"); 
$.Dialog.close({ "dialogresult": "cancel", "data": "" })
$.Dialog.openWindow(url)
$.Dialog.closeWindow()

*/
jQuery.Dialog = {
    //弹出提示窗口
    open: function (url, option, callback) {
        //调用方法打开对话框
        parent.openModalDialog(url, option, callback);
    },
    //关闭当前对话框
    close: function (result) {
        if (result == undefined)
            result = { "dialogresult": "cancel", "data": "" };
        //调用方法关闭对话框
        parent.closeModalDialog(result);
    },
    //打开新窗口
    openWindow: function (url,options, callback) {
        //调用方法打开对话框
        var defaults = { "window": window };
        var opt = $.extend({}, defaults, options);

        parent.openTabDialog(url, opt, callback);
    },
    closeWindow: function (result) {
        if (result == undefined)
            result = { "dialogresult": "cancel", "data": "" };
        //调用方法关闭对话框
        parent.closeTabDialog(result);
    }
}

/*
选择查询条件
name 选项名称
value 选中的值
submitForm 是否提交表单
*/

function selectedOption(name, value, submitForm) {
    $("#" + name).val(value);

    if (submitForm != undefined && submitForm) {
        $("form").eq(0).submit(); //提交表单
    }
}

//日期选择器
function datePicker(objID) {
    $(objID).datepicker({
        dateFormat: 'yy-mm-dd',
        dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
        monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        monthNamesShort: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        yearRange: '1950:2020',
        gotoCurrent: true,
        selectOtherMonths: true,
        showOtherMonths: true,
        changeMonth: true,
        changeYear: true,
        showButtonPanel: false,
        currentText: 'Now',
        showAnim: 'fold'
    });

    $(objID).addClass("datePicker");
}

//联动省市区.ID为 ProvinceID\CityID\AreaID
function initProvince(objID) {
    $(objID).change(function () {
        var url = "/SystemSetting/GetCitysJsonByParentID?ParentID=" + $(this).val();
        $("#CityID").empty();

        $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            completed: function () { alert("complete") },
            success: bindCity
        });
    });
}

function bindCity(jsonData) {
    if (jsonData.length > 0) {
        var options = "<option value='0'></option>";
        $(jsonData).each(function (i) {
            options += "<option value='" + this.ID + "'>" + this.Name + "</option>";
        })

        $("#CityID").append(options);
    }
}

function initCity(objID) {

    $(objID).change(function () {
        var url = "/SystemSetting/GetCitysJsonByParentID?ParentID=" + $(this).val();
        $("#AreaID").empty();

        $.ajax({
            url: url,
            type: "get",
            dataType: "json",
            completed: function () { alert("complete") },
            success: bindArea
        });
    });
}

function bindArea(jsonData) {
    if (jsonData.length > 0) {
        var options = "<option value='0'></option>";
        $(jsonData).each(function (i) {
            options += "<option value='" + this.ID + "'>" + this.Name + "</option>";
        })

        $("#AreaID").append(options);
    }
}

//----------------- cookie 操作 -----------------------------------
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof (days) == "number" && typeof (hours) == "number" && typeof (hours) == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}

//utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf(";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return;
}

// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
            ((expires) ? "; expires=" + expires : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
}

// remove the cookie by setting ancient expiration date
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}



/*----------------- jquery 插件 对于查询搜索框设计的查询按钮 -----------------------------------
用法： $(".searchBar").advSwitch();
参数： {}   
name 控件名称 默认空  
display 是否显示高级条件，默认false
*/
$.fn.advSwitch = function (options) {

    if ($(this).length == 0)
        return;

    var opts = $.extend({}, $.fn.advSwitch.defaults, options);
    var obj = $(this).eq(0);


    var cookieName = opts.name;
    if (cookieName == undefined || cookieName == "") {
        var url = window.location + "";
        var urls = url.split("/");
        var cookieName = urls[3] + "_" + urls[4]
    }

    var exprieTime = getExpDate(30, 0, 0);
    var cookieValue = getCookie(cookieName);
    var display = cookieValue == undefined || cookieValue == "1" ? true : false;
    if (cookieValue == undefined)
        display = opts.display;
    else
        display = cookieValue == "1" ? true : false;

    var oDiv = document.createElement("div");
    oDiv.id = "advSwitch";

    var oA = document.createElement("a");
    oA.innerHTML = "高级查询";
    oA.href = "javascript:void(0)";
    $(oA).click(function () {
        if (display) {
            oA.innerHTML = "高级查询";
            $(".adv", obj).hide();
            $(".unadv", obj).show();
        }
        else {
            oA.innerHTML = "隐藏高级查询";
            $(".adv", obj).show();
            $(".unadv", obj).hide();
        }

        display = !display;
        setCookie(cookieName, display ? "1" : 0, exprieTime, null, null, null);
    });

    oDiv.appendChild(oA);
    obj.append(oDiv);

    if (display) {
        oA.innerHTML = "隐藏高级查询";
        $(".adv", obj).show();
        $(".unadv", obj).hide();
    }
    else {
        oA.innerHTML = "高级查询";
        $(".adv", obj).hide();
        $(".unadv", obj).show();
    }
};

$.fn.advSwitch.defaults = {
    name: '',  //控件唯一标示名
    display: false //初始显示还是隐藏
};



/*----------------- jquery 插件 对于查询搜索框设计的查询按钮 -----------------------------------

调用方式：
$.Msg.alert("标题【可选】","内容","显示时间，毫秒【可选】,'显示的图标 alert,error【可选】'"); 
$.Msg.confirm("标题【可选】","内容","回调函数【可选】"); 

*/
jQuery.Msg = {
    //弹出提示窗口
    alert: function (title, content, timeout, icon) {
        if (title == "") title = "提示";
        var opt = { title: title, buttons: { 确定: true} };
        if (timeout != undefined)
            opt.timeout = timeout;

        if (icon != undefined && icon != "") {
            content = "<img class='icon' src='/images/icon/32x32/" + icon + ".png'/><p style='line-height:35px;'>" + content + "</p>";
        }

        $.prompt(content, opt);
    },
    confirm: function (title, content, fnSuccess) {
        if (title == "") title = "提示";
        var opt = {
            title: title,
            buttons: { 确定: true, 取消: false },
            submit: function (v, m, f) {
                $.prompt.close()
                if (v) fnSuccess();
            }
        };

        $.prompt(content, opt);
    },
    confirmDelete: function (fnSuccess) {
        var msg = "<img class='icon' src='/images/icon/32x32/alert.png'/><p style='line-height:35px;'>您确定要删除吗？删除后数据将不可恢复</p>";
        this.confirm("提示", msg, fnSuccess);
    },
    errorTips: function (title, msgType, errorList) {
        var obj = $("#actMessage");
        if (obj.length != 0) obj.remove();

        if (errorList == null || errorList.length == 0) {
            return;
        }

        var div = document.createElement("div");
        div.id = "actMessage";
        div.className = "actMessage error";

        var head = document.createElement("h");
        head.innerHTML = title;
        var closeTips = document.createElement("a");
        closeTips.innerHTML = "关闭";
        closeTips.className = "errorTips";
        closeTips.href = "javascript: closeErrorTips()";
        closeTips.title = "关闭这个错误提示?";
        var ul = document.createElement("ul");
        ul.id = "messages";
        for (var i = 0; i < errorList.length; i++) {
            var li = document.createElement("li");
            li.innerHTML = errorList[i].message;
            ul.appendChild(li);
        }
        try {
            div.appendChild(head);
            div.appendChild(closeTips);
            div.appendChild(ul);
            $(div).insertAfter(".navTitle:first");
            $(parent).scrollTop(0);
        } catch (e) {
            window.scrollTo(0, 0);
        }

    }
};
function closeErrorTips() {
    $("#actMessage").hide();
}

/*----------------- jquery 插件 控件 -----------------------------------

调用方式：
$.ctrl.checked("jquery选择器");    选中或反选复选框
$.ctrl.getCheckedValue("jquery 复选框选择器","jquery 目标值选择器");    获取选中复选框对应的目标值
*/
jQuery.ctrl = {
    checked: function (selector) {
        $(selector).each(function (i) {
            var r = $(this).attr("checked");
            if (r == undefined) r = false;
            $(this).attr("checked", !r)
        })
    },
    test: function () {
        alert(1);
    },
    getCheckedValue: function (selectorCheckboxs, selectorTargets) {
        var tars = $(selectorTargets);
        var values = "";
        $(selectorCheckboxs).each(function (i) {
            var r = $(this).attr("checked");
            if (r == true)
                values += tars.eq(i).val() + ",";
        })

        if (values.length > 0)
            values = values.substr(0, values.length - 1);
        return values;
    },
    //员工下拉框 txtID 文本框ID valID 值框ID
    employeeDropdownList: function (txtID, valID) {
        $("#" + txtID).combobox({
            ColumnsMapsNodeName: 'UserID|Name',
            TagObject: document.getElementById(valID),
            MustMatching: false,
            ListWidth: 250,
            DisplayHead: true,
            ListType: ListType.Combobox,
            DataType: DataType.Xml,
            DataLoadOnce: false,
            RemoteUrl: "/data/getxmldata?datatype=employee&keyword=",
            TextFormat: 'V1',
            ValueFormat: 'V0',
            HeadColumn: [
            { name: "编号", width: 60 },
            { name: "名称" }
            ],
            KeyWordColumn: ''
        });
    },

    //数据字典   jobj jquery查找的对象，objV 值对象，javascript 的dom对象
    dictDropdownList: function (jobj, objV, dictKey) {
        var editUrl = "/Dict/Manage?dictKey=" + dictKey;

        jobj.combobox({
            ColumnsMapsNodeName: 'ID|Name',
            TagObject: objV,
            MustMatching: true,
            ListWidth: 250,
            DisplayHead: true,
            ListType: ListType.Combobox,
            DataType: DataType.Xml,
            DataLoadOnce: false,
            RemoteUrl: "/data/getxmldata?datatype=dict&dictKey=" + dictKey + "&keyword=",
            TextFormat: 'V1',
            ValueFormat: 'V0',
            HeadColumn: [
            { name: "编号", width: 60 },
            { name: "名称" }
            ],
            KeyWordColumn: '',
            Buttons: [
            { text: "添加", event: function () { parent.showModalDialog(editUrl, false); } }
            ]
        });
    },
    //企业下拉框 txtID 文本框ID valID 值框ID,fnEvent,OnItemClickEvent回调函数
    enterpriseDropdownList: function (txtID, valID, fnEvent) {
        $("#" + txtID).combobox({
            ColumnsMapsNodeName: 'UserID|Name|Linkman|LinkmanTel|MobileNo|Fax',
            TagObject: document.getElementById(valID),
            MustMatching: false,
            ListWidth:450,
            DisplayHead: true,
            ListType: ListType.Combobox,
            DataType: DataType.Xml,
            DataLoadOnce: false,
            RemoteUrl: "/data/getxmldata?datatype=enterpriseMember&keyword=",
            TextFormat: 'V1',
            ValueFormat: 'V0',
            OnItemClickEvent: fnEvent,
            HeadColumn: [
                        { name: "编号", width: 60, display: false },
                        { name: "单位名称", width: 200 },
                        { name: "联系人", width: 100, display: true },
                        { name: "联系电话", width: 150, display: true },
                         { name: "手机", width: 60, display: false },
                          { name: "Fax", width: 60, display: false },
                        ],
            KeyWordColumn: '',
            Buttons:
            [
            { text: "添加", event: function () { parent.showModalDialog('/Account/EditEnterpriseMember', false); } }
            ]
        });
    },
    //企业下拉框 txtID 文本框ID valID 值框ID,fnEvent,OnItemClickEvent回调函数
    enterpriseUnEditDropdownList: function (txtID, valID, fnEvent) {
        $("#" + txtID).combobox({
            ColumnsMapsNodeName: 'UserID|Name|Linkman|LinkmanTel|MobileNo|Fax',
            TagObject: document.getElementById(valID),
            MustMatching: false,
            ListWidth: 250,
            DisplayHead: true,
            ListType: ListType.Combobox,
            DataType: DataType.Xml,
            DataLoadOnce: false,
            RemoteUrl: "/data/getxmldata?datatype=enterpriseMember&keyword=",
            TextFormat: 'V1',
            ValueFormat: 'V0',
            OnItemClickEvent: fnEvent,
            HeadColumn: [
                        { name: "编号", width: 60, display: false },
                        { name: "单位名称", width: 120 },
                        { name: "联系人", width: 60, display: false },
                        { name: "联系电话", width: 60, display: true },
                         { name: "手机", width: 60, display: false },
                          { name: "Fax", width: 60, display: false },
                        ],
            KeyWordColumn: ''
        });
    },
    //企业下拉框 txtID 文本框ID valID 值框ID,fnEvent,OnItemClickEvent回调函数
    enterDropdownList: function (txtID, valID, type, isTeamPlan, fnEvent) {
        

        $("#" + txtID).combobox({
            ColumnsMapsNodeName: 'UserID|Name|Linkman|LinkmanTel|MobileNo|Fax|EnAlias|CityName',
            TagObject: document.getElementById(valID),
            MustMatching: false,
            ListWidth: 450,
            DisplayHead: true,
            ListType: ListType.Combobox,
            DataType: DataType.Xml,
            DataLoadOnce: false,
            RemoteUrl: "/data/getxmldata?datatype=enterpriseMember&EnterpriseType=" + type + "&isTeamPlan=" + isTeamPlan + "&keyword=",
            TextFormat: 'V1',
            ValueFormat: 'V0,V1,V2,V3,V4,V5,V6,V7',
            OnItemClickEvent: fnEvent,
            HeadColumn: [
                        { name: "编号", width: 60, display: false },
                        { name: "单位名称", width: 250 },
                        { name: "联系人", width: 60, display: false },
                        { name: "联系电话", width: 100, display: true },
                         { name: "手机", width: 60, display: false },
                          { name: "Fax", width: 60, display: false },
                          { name: "英文简称", width: 60, display: false },
                          { name: "城市名", width: 100, display: true },
                        ],
            KeyWordColumn: ''
        });
    },
    //数据字典   jobj jquery查找的对象，objV 值对象，javascript 的dom对象
    enterNofunDropdownList: function (jobj, objV) {
        jobj.combobox({
            ColumnsMapsNodeName: 'UserID|Name',
            TagObject: objV,
            MustMatching: true,
            ListWidth: 250,
            DisplayHead: true,
            ListType: ListType.Combobox,
            DataType: DataType.Xml,
            DataLoadOnce: false,
            RemoteUrl: "/data/getxmldata?datatype=enterpriseMember&keyword=",
            TextFormat: 'V1',
            ValueFormat: 'V0',
            HeadColumn: [
            { name: "编号", width: 60 },
            { name: "名称" }
            ],
            KeyWordColumn: '',
            Buttons: [
            { text: "添加", event: function () { parent.showModalDialog('/Account/EditEnterpriseMember', false); } }
            ]
        });
    },
    //付款方式
    PayModeDropdownList: function (jobj, objV) {
        var jsondata = [
            ["1", "现金"],
             ["2", "签单"],
              ["3", "财务付款"]
            ];
        jobj.combobox({
            TagObject: objV,
            MustMatching: true,
            ListWidth: 250,
            DisplayHead: true,
            ListType: ListType.Combobox,
            DataType: DataType.Json,
            DataSource: jsondata,
            DataLoadOnce: false,
            TextFormat: 'V1',
            ValueFormat: 'V0',
            HeadColumn: [
            { name: "编号", width: 60 },
            { name: "名称" }
            ],
            KeyWordColumn: ''
        });
    }
}
